<?php
/**
 * Events.php
 *
 * Niushop商城系统 - 团队十年电商经验汇集巨献!
 * =========================================================
 * Copy right 2015-2025 山西牛酷信息科技有限公司, 保留所有权利。
 * ----------------------------------------------
 * 官方网址: http://www.niushop.com.cn
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用。
 * 任何企业和个人不允许对程序代码以任何形式任何目的再发布。
 * =========================================================
 * @author : niuteam
 * @date : 2015.1.17
 * @version : v1.0.0.0
 */
namespace data\service;

use data\model\NsGoodsSkuModel;
use data\model\NsGoodsModel;
use data\model\NsShopModel;
use data\model\NsCartModel;
use data\service\Order\OrderGoods;
use data\service\promotion\GoodsPreference;
use data\model\AlbumPictureModel;
use data\service\promotion\GoodsMansong;
use data\service\promotion\GoodsExpress;
use data\service\Member\MemberCoupon;
use data\model\UserModel;
use data\model\NsPromotionFullMailModel;
use data\model\NsOrderModel;
use data\service\Order\Order as OrderBusiness;
use data\model\NsOrderPaymentModel;
use data\service\Order\OrderStatus;
use data\service\Order\OrderExchange;
use data\service\Order\OrderGroupBuy;
/**
 * 多商户订单类
 * @author Administrator
 *
 */
class ShopOrder extends Order{
    
    function __construct()
    {
        parent::__construct();
    }
    /**
     * 商品按照店铺拆分
     * @param unknown $goods_sku_list
     * @param unknown $order_type  1 为普通订单    2 位虚拟订单 3 团购订单 4组合套餐 5
     * @param unknown $param 参数
     */
    public function goodsSkuListSplit($goods_sku_list, $order_type = 1, $param = [])
    {
        
        //查询用户默认收货地址
        $count_money = 0;
        $count_discount_money = 0;
        $count_express = 0;
        $count_goods_money = 0;
        $count_goods_num = 0;//商品种类数量
        $count_array = array();
        $count_points = 0;
        $shop = new Shop();
        $member = new Member();
        $config= new Config();
        $promotion = new Promotion();
        $order_exchange = new OrderExchange();//用于积分兑换
        
        //店铺配置
        $config_info = $config->getShopConfig(0);
        $order_invoice_content = explode(",", $config_info['order_invoice_content']);
        $config_info['order_invoice_content_list'] = array();
        foreach ($order_invoice_content as $u) {
            if (! empty($u)) {
                array_push($config_info['order_invoice_content_list'], $u);
            }
        }
        $goods_express_service = new GoodsExpress();
        if($order_type == 2){
            $address = array();
        }else{
            $address = $member->getDefaultExpressAddress();
        }
        //商品按照店铺拆分
        $shop_goods_array = $this->goodsSkuListShopSplit($goods_sku_list);
        $goods_mansong = new GoodsMansong();
        
        //循环商品进行数据分组获取优惠券
        foreach ($shop_goods_array as $k => $v)
        {
        	
            $count_money = 0;//总金额
            $express_money = 0;//店铺运费
            $discount_money = 0;//优惠金额
            $is_open_o2o_distribution = 0;//是否开启本地配送
            $o2o_distribution = array();//本地配送设置
            $distribution_time = "";//配送时间
            $goods_mansong_gifts = array();//赠品
            if(empty($v["sku_list_array"])) $v["sku_list_array"] = [];
            $shop_goods_array[$k]['shop_goods_num'] = count($v["sku_list_array"]); //商品种类数量
            $count_goods_num += count($v["sku_list_array"]); //商品种类数量
            
            $shop_goods_array[$k]["config"] = $config_info;//配置
            foreach($v["sku_list_array"] as $goods_key => $goods_val){
                if($order_type == 3){//如果是团购商品的话  商品单价用团购价替换
                    $order_group_buy = new OrderGroupBuy();
                    $price =  $order_group_buy ->getGoodsGroupBuyUnitPrice($goods_val['goods_id'], $goods_val['num']);
                    $shop_goods_array[$k]["sku_list_array"][$goods_key]["price"] = sprintf("%.2f", $price);
                    $shop_goods_array[$k]["sku_list_array"][$goods_key]["subtotal"] = sprintf("%.2f", $price * $goods_val['num']);
                }else{
                    $shop_goods_array[$k]["sku_list_array"][$goods_key]["price"] = sprintf("%.2f", $shop_goods_array[$k]["sku_list_array"][$goods_key]["price"]);
                    $shop_goods_array[$k]["sku_list_array"][$goods_key]["subtotal"] = sprintf("%.2f", $shop_goods_array[$k]["sku_list_array"][$goods_key]["subtotal"]);
                }
            }
          
            //商品金额
            if($order_type == 3){
                //团购总计算   (如果是团购 用团购价计算)
                $group_buy_order = new OrderGroupBuy();
                $goods_money = sprintf("%.2f", $group_buy_order->getGoodsSkuGroupBuyPrice($goods_sku_list)); // 商品金额
            }else{
                $goods_money = sprintf("%.2f", $this->getGoodsSkuListPrice($v["goods_sku_list"])); // 商品金额
            }
            
            if($order_type == 4){
                //当订单为组合套时 , 查询组合套餐详情
                $promotion = new Promotion();
                $combo_detail = $promotion->getComboPackageDetail($param["combo_id"]);
                $combo_detail["combo_buy_num"] = $param["combo_buy_num"];
                $goods_money = sprintf("%.2f",$combo_detail["combo_package_price"] * $param["combo_buy_num"]);
                $combo_detail["count_combo_money"] = $combo_detail["combo_package_price"] * $param["combo_buy_num"];
                $shop_goods_array[$k]["combo_detail"] = $combo_detail;
            }

            
            //商品积分
            $goods_points = $order_exchange->getGoodsOrderPoint($v["goods_sku_list"]);//用于积分兑换
            $count_points += $goods_points;
            
            if($order_type != 3 && $order_type != 4){//团购不参与优惠金额以及活动
                $coupon_list = $this->getMemberCouponList($v['goods_sku_list'], $v["shop_id"]); // 获取优惠券
                foreach ($coupon_list as $k_coupon => $v_coupon) {
                    $coupon_list[$k_coupon]['start_time'] = substr($v_coupon['start_time'], 0, stripos($v_coupon['start_time'], " ") + 1);
                    $coupon_list[$k_coupon]['end_time'] = substr($v_coupon['end_time'], 0, stripos($v_coupon['end_time'], " ") + 1);
                }
            }
            $shop_goods_array[$k]['coupon_list'] = $coupon_list;
            
            if($order_type != 3){//团购不参与优惠金额以及活动
                // 计算优惠金额
                if($order_type == 4){
                    // 组合套餐 计算优惠金额
                    $discount_money = $goods_money - $combo_detail["count_combo_money"];
                }else{
                    $discount_money = $goods_mansong->getGoodsMansongMoney($v["goods_sku_list"], $v["shop_id"]); 
                }
                
            }
            $discount_money = $discount_money < 0 ? 0 : $discount_money;//优惠不能小于0
            $shop_goods_array[$k]['discount_money'] = sprintf("%.2f", $discount_money);
            //店铺物流
            $express = 0;
            $express_company_list = array();
           
            if($order_type != 2){//虚拟订单不计算物流
                //判断是否开启商家配送
                if($config_info["seller_dispatching"]){
                    if (! empty($address)) {
                        //获取本店铺下的物流公司
                        $express_company_list = $goods_express_service->getExpressCompany($v["shop_id"], $v["goods_sku_list"], $address['province'], $address['city'], $address['district']);
                        if (! empty($express_company_list)) {
                            foreach ($express_company_list as $t) {
                                $express = sprintf("%.2f", $t['express_fee']); // 取第一个运费，初始化加载运费
                                break;
                            }
                        }else{
                            $express_company_list = array();
                        }
                        //计算商品所在店铺所设置的本地配送
                        $o2o_distribution = $goods_express_service->getGoodsO2oPrice($goods_money - $discount_money, $v["shop_id"], $address['province'], $address['city'], $address['district'], 0);
                        if($o2o_distribution >= 0)
                        {
                            $is_open_o2o_distribution = 1;
                        }
                    }
                    //只要物流开启运费有限计算物流
                    $express_money = $express;
                }
            }
            //多用户订单默认选择默认物流模板
            $shop_goods_array[$k]["express_fee"] = sprintf("%.2f", $express); //店铺下的默认物流运费
            $shop_goods_array[$k]["express_company_list"] = $express_company_list; //店铺下的物流公司
//             $count = $goods_express_service->getExpressCompanyCount($v["shop_id"]);
            $pickup_point_list = array();
            $pick_up_money = 0;
            
            if($order_type != 2){//判断虚拟商品没有自提订单
                //判断店铺是否开启门店自提
                if($config_info["buyer_self_lifting"]){
                    //自提点
                    $pickup_point_list = $shop->getPickupPointList(1 ,0 , ["shop_id"=>$v["shop_id"]], '');
                    //自提点运费
                    $pick_up_money = $this->getPickupMoney($goods_money, $v["shop_id"]);//自提点运费
                    if (empty($pick_up_money)) {
                        $pick_up_money = 0;
                    }
                    //如果店铺物流未开启,运费优先计算门店自提
                    if(!$config_info["seller_dispatching"]){
                        $express_money = $pick_up_money;
                    }
                }
            }
            $shop_goods_array[$k]["pickup_point_list"] = $pickup_point_list; //自提点列表

            
            $count_discount_money -= $discount_money;
            $count_express += $express_money;
            $count_goods_money += $goods_money;
            
            $count_money += $goods_money - $discount_money;
            $shop_goods_array[$k]["goods_money"] = sprintf("%.2f", $goods_money);
            $shop_goods_array[$k]["pick_up_money"] = sprintf("%.2f", $pick_up_money);
            $shop_goods_array[$k]["count_money"] = sprintf("%.2f", $count_money);
            $shop_goods_array[$k]["count_points"] = $count_points;
            $shop_goods_array[$k]["express_money"] = sprintf("%.2f", $express_money);
            $shop_goods_array[$k]["count_point"] = $goods_points;
            
            $shop_goods_array[$k]["is_open_o2o_distribution"] = $is_open_o2o_distribution;
            $shop_goods_array[$k]["o2o_distribution"] = $o2o_distribution;
            
            if($order_type != 2){  //虚拟商品不参与物流
                //本地配送时间
                $distribution_time = $this->getDistributionTime($v["shop_id"]);
            }
            $shop_goods_array[$k]["distribution_time"] = $distribution_time;
            $promotion_full_mail = array();
            if($order_type != 2){
                //店铺满额包邮信息
                $promotion_full_mail = $promotion->getPromotionFullMail($v["shop_id"]);
                if (! empty($address)) {
                    $no_mail = checkIdIsinIdArr($address['city'], $promotion_full_mail['no_mail_city_id_array']);
                    if (!$no_mail) {
                        $promotion_full_mail['is_open'] = 0;
                    }
                }
            }
            $shop_goods_array[$k]["promotion_full_mail"] = $promotion_full_mail;
            
            //赠品
            if($order_type == 1 || $order_type == 2){
                $goods_mansong_gifts = $this->getOrderGoodsMansongGifts($v["goods_sku_list"], $v["shop_id"]);
            }
            $shop_goods_array[$k]["goods_mansong_gifts"] = $goods_mansong_gifts;
            
        }
        $count_array["shop_goods_array"] = $shop_goods_array;
        $count_array["count_info"] = array(
            "count_discount_money" => $count_discount_money,
            "count_express" => $count_express,
            "count_goods_money" => $count_goods_money,
            "count_money" => $count_money,
            "count_goods_num" => $count_goods_num,
            "count_points" => $count_points
        );
        $count_array["address"] = $address;
        return $count_array;
    }
    /**
     * 商品分组按照店铺拆分(将商品拆分成对应不同的分组组合,每个组合包含shopid，shop_name)
     * @param unknown $goods_lku_list
     */
   public function goodsSkuListShopSplit($goods_sku_list)
   {
       $split_array = array();
       if(!empty($goods_sku_list))
       {
           $goods_sku_list_array = explode( ",", $goods_sku_list);
           foreach ($goods_sku_list_array as $k => $v)
           {
               $sku_data = explode(":", $v);
               $sku_id = $sku_data[0];
               $sku_count = $sku_data[1];
               //查询商品对应的单品价格以及店铺
               $goods_sku_model = new NsGoodsSkuModel();
               $goods_sku_info = $goods_sku_model->getInfo(['sku_id' => $sku_id], 'goods_id');
               $goods_model = new NsGoodsModel();
               $goods_info = $goods_model->getInfo(['goods_id' => $goods_sku_info['goods_id']], 'shop_id');
               $goods_sku_data = $this->getSkuInfo($sku_id, $sku_count);
               if(empty($split_array[$goods_info['shop_id']]))
               {
                   $shop_goods_sku = $v;
                   $shop_model = new NsShopModel();
                   $shop_info = $shop_model->getInfo(['shop_id' => $goods_info['shop_id']], 'shop_name');
                   
                   $split_array[$goods_info['shop_id']] = array(
                       'shop_id'    => $goods_info['shop_id'],
                       'shop_name'  => $shop_info['shop_name'],
                       'goods_sku_list' => $shop_goods_sku
                   );
                   $split_array[$goods_info['shop_id']]['sku_list_array'] = array();
                   $split_array[$goods_info['shop_id']]['sku_list_array'][] = $goods_sku_data;
               }else{
                   $shop_id = $goods_info['shop_id'];
                   $split_array[$shop_id]['goods_sku_list'] = $split_array[$shop_id]['goods_sku_list'].','.$v;
                   $split_array[$shop_id]['sku_list_array'][] = $goods_sku_data;
               } 
              
           }
       
       }
       return $split_array;
   }
   /**
    * 获取商品sku购买信息
    * @param unknown $sku_id
    * @param unknown $num
    */
   public function getSkuInfo($sku_id, $num)
   {
       $cart_list = array();
       
       // 获取商品sku信息
       $goods_sku = new NsGoodsSkuModel();
       $sku_info = $goods_sku->getInfo([
           'sku_id' => $sku_id
       ], '*');
       
       // 查询当前商品是否有SKU主图
       $order_goods_service = new OrderGoods();
       $picture = $order_goods_service->getSkuPictureBySkuId($sku_info);
       
       // 清除非法错误数据
       $cart = new NsCartModel();
       if (empty($sku_info)) {
           $cart->destroy([
               'buyer_id' => $this->uid,
               'sku_id' => $sku_id
           ]);
       
       }
       
       $goods = new NsGoodsModel();
       $goods_info = $goods->getInfo([
           'goods_id' => $sku_info["goods_id"]
       ], 'max_buy,state,point_exchange_type,point_exchange,picture,goods_id,goods_name');
       //获取订单商品店铺信息
       $cart_list["stock"] = $sku_info['stock']; // 库存
       $cart_list["sku_name"] = $sku_info["sku_name"];
       
       $goods_preference = new GoodsPreference();
       $member_price = $goods_preference->getGoodsSkuMemberPrice($sku_info['sku_id'], $this->uid);
       $cart_list["price"] = $member_price < $sku_info['promote_price'] ? $member_price : $sku_info['promote_price'];
       $cart_list["goods_id"] = $goods_info["goods_id"];
       $cart_list["goods_name"] = $goods_info["goods_name"];
       $cart_list["max_buy"] = $goods_info['max_buy']; // 限购数量
       $cart_list['point_exchange_type'] = $goods_info['point_exchange_type']; // 积分兑换类型 0 非积分兑换 1 只能积分兑换
       $cart_list['point_exchange'] = $goods_info['point_exchange']; // 积分兑换
       
       $cart_list["num"] = $num;
       $goods_service = new Goods();
       $cart_list["price"] = $goods_service->getGoodsLadderPreferentialInfo($goods_info["goods_id"], $num, $cart_list["price"]);
       $cart_list["subtotal"] = $num * $cart_list["price"];
       // 如果购买的数量超过限购，则取限购数量
       if ($goods_info['max_buy'] != 0 && $goods_info['max_buy'] < $num) {
           $num = $goods_info['max_buy'];
       }
       // 如果购买的数量超过库存，则取库存数量
       if ($sku_info['stock'] < $num) {
           $num = $sku_info['stock'];
       }
       // 获取图片信息，如果该商品有SKU主图，就用。否则用商品主图
       $album_picture_model = new AlbumPictureModel();
       $picture_info = $album_picture_model->get($picture == 0 ? $goods_info['picture'] : $picture);
       $cart_list['picture_info'] = $picture_info;
       

       return $cart_list;
       
   }
   /**
    * 多店版订单生成
    * @param unknown $order_type
    * @param unknown $out_trade_no
    * @param unknown $pay_type
    * @param unknown $shipping_type
    * @param unknown $order_from
    * @param unknown $buyer_ip
    * @param unknown $buyer_message
    * @param unknown $buyer_invoice
    * @param unknown $shipping_time
    * @param unknown $receiver_mobile
    * @param unknown $receiver_province
    * @param unknown $receiver_city
    * @param unknown $receiver_district
    * @param unknown $receiver_address
    * @param unknown $receiver_zip
    * @param unknown $receiver_name
    * @param unknown $point   默认为0 (不实际使用)
    * @param unknown $coupon_id $shop_id,$coupon_id; $shop_id,$coupon_id
    * @param unknown $user_money
    * @param unknown $goods_sku_list
    * @param unknown $platform_money
    * @param unknown $pick_up_id $shop_id,$pick_up_id; $shop_id,$pick_up_id
    * @param unknown $shipping_company_id $shop_id,$shop_shipping_company_id; $shop_id,$shop_shipping_company_id
    * @param number $coin
    * @param string $fixed_telephone
    */
   public function shopCreateOrder($order_type, $out_trade_no, $pay_type, $order_from, $buyer_ip, $buyer_message, $buyer_invoice, $shipping_time, $receiver_mobile, $receiver_province, $receiver_city, $receiver_district, $receiver_address, $receiver_zip, $receiver_name, $point, $coupon_id, $user_money, $goods_sku_list, $platform_money, $pick_up_id, $shipping_company_id, $coin = 0, $fixed_telephone = "", $shipping_type){
       $order_model = new NsOrderModel();
       $order_model->startTrans();
       
       try {
           //订单详情页
           $order_business = new OrderBusiness();
           if ($pay_type == 4) {
               // 如果是货到付款 判断当前地址是否符合货到付款的地址
               $address = new Address();
               $result = $address->getDistributionAreaIsUser(0, $receiver_province, $receiver_city, $receiver_district);
               if (! $result) {
                   return ORDER_CASH_DELIVERY;
               }
           }
           $shop_name = '';
           $shop_express_array = array();
           $shop_pick_array = array();
           $shop_coupon_array = array();
           $shop_buyer_message_array = array();//订单留言
           $shipping_time_array = array();//配送时间
           $shipping_type_array = array();//配送方式
           //拼装物流公司
           if($shipping_company_id != ""){
               $temp_array = explode(';',$shipping_company_id);
               foreach($temp_array as $k => $v){
                   $array = explode(',',$v);
                   $shop_express_array[$array[0]] =  $array[1];
                   
               }
           }
           //拼装自提点
           if($pick_up_id != ""){
               $temp_array = explode(';',$pick_up_id);
               foreach($temp_array as $k => $v){
                   $array = explode(',',$v);
                   $shop_pick_array[$array[0]] =  $array[1];
                    
               }
           }
           //拼装优惠券
           if($coupon_id != ""){
               $temp_array = explode(';',$coupon_id);
               foreach($temp_array as $k => $v){
                   $array = explode(',',$v);
                   $shop_coupon_array[$array[0]] =  $array[1];
               }
           }
           //拼装订单留言
           if($buyer_message != ""){
               $temp_array = explode(';',$buyer_message);
               foreach($temp_array as $k => $v){
                   $array = explode(',',$v);
                   $shop_buyer_message_array[$array[0]] =  $array[1];
                    
               }
           }
           //拼装配送时间
           if($shipping_time != ""){
                $temp_array = explode(';',$shipping_time);
                foreach($temp_array as $k => $v){
                    $array = explode(',',$v);
                    $shipping_time_array[$array[0]] =  $array[1];
                    
                }
            }
            //拼装配送方式
            if($shipping_type != ""){
                $temp_array = explode(';',$shipping_type);
                foreach($temp_array as $k => $v){
                    $array = explode(',',$v);
                    $shipping_type_array[$array[0]] =  $array[1];
                    
                }
            }
            $shop_goods_array = $this->goodsSkuListShopSplit($goods_sku_list);
        //    $shipping_time = getTimeTurnTimeStamp($shipping_time);
           //计算余额,将余额先给第一个店铺的订单
           if(!empty($shop_goods_array)){
               foreach($shop_goods_array as $k => $v){
                   $shop_name = $v["shop_name"];
                   $order_platform_money = 0;
                //    $shipping_type = 1;// 配送方式，1：物流，2：自提
                //    if ($shop_pick_array[$v["shop_id"]] != 0) {
                //        $shipping_type = 2;
                //    }
                //如果余额大于0,需要为各个订单分配余额
                   if($platform_money > 0){
                       //计算店铺商品订单金额
                       $order_money = $this -> countShopGoodsPrice($v["goods_sku_list"], $shop_coupon_array[$v["shop_id"]], $shipping_type_array[$v["shop_id"]], $shop_express_array[$v["shop_id"]], $receiver_province, $receiver_city, $receiver_district, $buyer_invoice);
                       if($platform_money >= $order_money){
                           //如果余额大于此订单的订单金额,则余额将减去本次订单,剩余的留给下一笔订单
                           $order_platform_money = $order_money;//本次订单所用余额
                           $platform_money = $platform_money - $order_money;//剩余余额
                       }else{
                           $order_platform_money = $platform_money;
                           $platform_money = 0;
                       }
                   }
                   //生成订单
                   $retval = $order_business -> orderCreate(1, $out_trade_no, $pay_type, $shipping_type_array[$v["shop_id"]], $order_from, $buyer_ip, $shop_buyer_message_array[$v["shop_id"]], $buyer_invoice, $shipping_time_array[$v["shop_id"]], $receiver_mobile, $receiver_province, $receiver_city, $receiver_district, $receiver_address, $receiver_zip, $receiver_name, $point, $shop_coupon_array[$v["shop_id"]], $user_money, $v["goods_sku_list"], $order_platform_money, $shop_pick_array[$v["shop_id"]], $shop_express_array[$v["shop_id"]], 0);
                   if($retval <= 0){
                       $order_model->rollback();
                       return $retval;
                   }else{
                       //订单创建成功提示
                       runhook("Notify", "orderCreate", array(
                       "order_id" => $retval
                       ));
                       
                       hook('orderCreateSuccess', [
                       'order_id' => $retval
                       ]);
                   }
               }
           }else{
               
               $order_model->rollback();
               return 0;
           }
           //支付交易创建
           $pay = new UnifyPay();
//         判断订单信息  (如果这笔支付订单 只存在,则将本次须支付金额也加入)
           $order_model = new NsOrderModel();
           $order_query = $order_model -> getQuery(["out_trade_no" => $out_trade_no], "order_id, pay_money, user_platform_money", '');
           if(empty($order_query)){
               $order_model->rollback();
               return 0;
           }
           $count_pay_money = 0;//订单交易的总支付金额
           $is_pay_money_null = true;//记录交易号下的订单实际支付金额是否都为0
           foreach($order_query as $k => $v){
               $count_pay_money += $v["pay_money"];
               if($v["pay_money"] == 0){
                   // 订单转为待发货状态
                   $data = array(
                       'pay_status' => 2,
                       'pay_time' => time(),
                       'order_status' => 1
                   ); 
                   //判断订单是否是余额支付
                   if($v["user_platform_money"] != 0){
                       //余额支付
                       $result = $this->orderInfoPay($v["order_id"], 5);
                       if($result <= 0){
                           $order_model->rollback();
                           return 0;
                       }
                       
                   }else{
                       //默认认为是微信支付支付
                       $result = $this->orderInfoPay($v["order_id"], 1);
                       if($result <= 0){
                           $order_model->rollback();
                           return 0;
                       }
                   }
               }else{
                   $is_pay_money_null = false;
               }
           }
           //创建订单交易
           $pay->createPayment(0, $out_trade_no, $shop_name . "订单", $shop_name . "订单", $count_pay_money, 1, 0);
           // 货到付款
           if ($pay_type == 4) {
               $this->orderOnLinePay($out_trade_no, 4);
           } else {
               //判断此支付集合下有无待支付的金额, 如果当中的订单全部都是余额抵消后的待支付金额为0的话,两笔订单都变为待发货状态
               if($is_pay_money_null){
                   $this->orderOnLinePay($out_trade_no, 1);
               }
           }
           
           $order_model->commit();
           return 1;
        } catch (\Exception $e) {
            $order_model->rollback();
            return $e->getMessage();
        }
   }
   /**
    * 计算订单的待支付金额
    * @param unknown $goods_sku_list
    * @param unknown $coupon_id
    * @param unknown $shipping_type
    * @param unknown $shipping_company_id
    * @param unknown $receiver_province
    * @param unknown $receiver_city
    * @param unknown $receiver_district
    * @param unknown $buyer_invoice
    * @param unknown $platform_money
    * @return Ambigous <string, \data\service\promotion\Ambigous, unknown, number, unknown>
    */
   public function countShopGoodsPrice($goods_sku_list, $coupon_id, $shipping_type,  $shipping_company_id, $receiver_province, $receiver_city, $receiver_district, $buyer_invoice){
       // 查询商品对应的店铺ID
       $order_goods_preference = new GoodsPreference();
       $shop_id = $order_goods_preference->getGoodsSkuListShop($goods_sku_list);
       // 单店版查询网站内容
       $shop_model = new NsShopModel();
       $shop_info = $shop_model->getInfo(['shop_id' => $shop_id], 'shop_name');
       $shop_name = $shop_info['shop_name'];
       // 获取优惠券金额
       $coupon = new MemberCoupon();
       $coupon_money = $coupon->getCouponMoney($coupon_id);
       
       $goods_money = $order_goods_preference->getGoodsSkuListPrice($goods_sku_list);
       // 获取订单邮费,订单自提免除运费
       if ($shipping_type == 1) {
           $order_goods_express = new GoodsExpress();
           $deliver_price = $order_goods_express->getSkuListExpressFee($goods_sku_list, $shipping_company_id, $receiver_province, $receiver_city, $receiver_district);
           if ($deliver_price < 0) {
               return $deliver_price;
           }
       } else {
           // 根据自提点服务费用计算
           $deliver_price = $order_goods_preference->getPickupMoney($goods_money, $shop_id);
       }

        $point_money = 0;
        // 订单待支付
        $order_status = 0;
        // 订单满减送活动优惠
        $goods_mansong = new GoodsMansong();
        $mansong_array = $goods_mansong->getGoodsSkuListMansong($goods_sku_list, $shop_id);
        $promotion_money = 0;
        $mansong_rule_array = array();
        $mansong_discount_array = array();
        if (! empty($mansong_array)) {
            foreach ($mansong_array as $k_mansong => $v_mansong) {
                foreach ($v_mansong['discount_detail'] as $k_rule => $v_rule) {
                    $rule = $v_rule[1];
                    $discount_money_detail = explode(':', $rule);
                    $mansong_discount_array[] = array(
                        $discount_money_detail[0],
                        $discount_money_detail[1],
                        $v_rule[0]['rule_id']
                    );
                    $promotion_money += $discount_money_detail[1]; // round($discount_money_detail[1],2);
                    // 添加优惠活动信息
                    $mansong_rule_array[] = $v_rule[0];
                }
            }
            $promotion_money = round($promotion_money, 2);
        }
        $full_mail_array = array();
        // 计算订单的满额包邮
        $full_mail_model = new NsPromotionFullMailModel();
        // 店铺的满额包邮
        $full_mail_obj = $full_mail_model->getInfo(["shop_id" => $shop_id], "*");
        $no_mail = checkIdIsinIdArr($receiver_city, $full_mail_obj['no_mail_city_id_array']);
        if ($no_mail) {
            $full_mail_obj['is_open'] = 0;
        }
        if (! empty($full_mail_obj)) {
            $is_open = $full_mail_obj["is_open"];
            $full_mail_money = $full_mail_obj["full_mail_money"];
            $order_real_money = $goods_money - $promotion_money - $coupon_money - $point_money;
            if ($is_open == 1 && $order_real_money >= $full_mail_money && $deliver_price > 0) {
                $deliver_price = 0;
            }
        }

        // 订单费用(具体计算)
        $order_money = $goods_money + $deliver_price - $promotion_money - $coupon_money - $point_money;

        if ($order_money < 0) {
            $order_money = 0;
        }
        if (! empty($buyer_invoice)) {
            // 添加税费
            $config = new Config();
            $tax_value = $config->getConfig(0, 'ORDER_INVOICE_TAX');
            if (empty($tax_value['value'])) {
                $tax = 0;
            } else {
                $tax = $tax_value['value'];
            }
            $tax_money = $order_money * $tax / 100;
        } else {
            $tax_money = 0;
        }
        $order_money = $order_money + $tax_money;

        return $order_money;
   }
   
   /**
    * 针对订单支付日志及状态的改变
    * @param unknown $order_id
    * @param unknown $pay_type
    */
   public function orderInfoPay($order_id, $pay_type){
       
       $order_pay_no = $this->modifyOrderOutTradeNo($order_id);//重新分配一个支付交易号
       
       $order_bus = new OrderBusiness();
       $retval = $order_bus -> OrderPay($order_pay_no, $pay_type, 1);//执行订单订单操作
       if($retval > 0){
           
           //计算店铺内部的分销佣金
           //处理店铺的账户资金
           //订单支付后的操作
           $this->orderFollowUpOperation($order_pay_no);
           //订单支付后的操作
           $this->orderPayFollowUp($order_pay_no, $pay_type);
           
       }
       return $retval;

   }
   
   /**
    * 订单的线下支付
    * @param unknown $order_id
    * @param unknown $pay_type
    * @param unknown $status
    */
   public function offlinePay($order_id, $pay_type, $status){
       
       $order_model = new NsOrderModel();
       try {
           $order_info =  $order_model -> getInfo(["order_id" => $order_id], "out_trade_no, pay_money");
           if(empty($order_info)){
               return 0;
           }
           
           $order_bus = new OrderBusiness();
           //生成一个新的支付交易号
           $new_no = $order_bus->createOutTradeNo();
           //重新生成外部交易号,并且生成一笔新的支付交易
           $pay = new UnifyPay();
           $pay->createPayment(0, $new_no,  "订单",  "订单", $order_info["pay_money"], 1, 0);
           //将线下支付的订单
           $data = array("out_trade_no" => $new_no);
           $retval = $order_model ->save($data, ["order_id" => $order_id]);
           //操作单笔订单, 并完成支付
           $retval = $this->orderInfoPay($order_id, $pay_type);
           
           return 1;
       } catch (\Exception $e) {
           return 0;
       }
   }
   /**
    * (non-PHPdoc)
    * @see \data\service\Order::getOrderNewOutTradeNo()
    */
   public function getOrderNewOutTradeNo($order_id){
       //给订单分配新的支付交易号
       $this->paymentOrderSplit($order_id);
       $order_model = new NsOrderModel();
       $order_info = $order_model -> getInfo(["order_id" => $order_id], "out_trade_no");
       $out_trade_no = "";
       if(!empty($order_info)){
           $out_trade_no = $order_info["out_trade_no"];
       }
       return $out_trade_no;
   }
   /**
    * 多订单 支付拆分
    * @param unknown $order_id
    */
   public function paymentOrderSplit($order_id){
       $order_model = new NsOrderModel();
       try {
           $orderinfo = $order_model -> getInfo(["order_id" => $order_id, "pay_status" => 0], "out_trade_no");
           if(!empty($orderinfo)){
               $order_list = $order_model -> getQuery(["out_trade_no" => $orderinfo["out_trade_no"]], "order_id", '');
               if(count($order_list) > 1){
                   foreach($order_list as $k => $v){
                       //订单生成新的支付编号
                       $this->orderModifyOutTradeNo($v["order_id"]);
                   }
                   //调用让原来的支付交易号在微信或支付宝里失效(通知第三方)
                   $pay = new UnifyPay();
                   $pay->closePaymentPartyInterface($orderinfo["out_trade_no"]);
                   $pay->delPayment($orderinfo["out_trade_no"]);
               }
           }
           return 1;
       } catch (\Exception $e) {
           return 0;
       }
   }
    
   /**
    * 订单变更支付交易号
    */
   public function orderModifyOutTradeNo($order_id){
       $order_model = new NsOrderModel();
       $order_bus = new OrderBusiness();
       $order_info = $order_model -> getInfo(["order_id" => $order_id,"pay_status" => 0], "out_trade_no, pay_money");
       $retval = 0;
       if(!empty($order_info)){
           //生成新的外部交易号
           $new_order_no = $order_bus->createOutTradeNo();
           $data = array(
               "out_trade_no" => $new_order_no
           );
           //创建新的外部交易号
           $pay = new UnifyPay();
           $pay->createPayment(0, $new_order_no,  "订单",  "订单", $order_info["pay_money"], 1, $order_id);
           
           $retval = $order_model ->save($data, ["order_id" => $order_id]);
       }
       return $retval;
   }
   /**
    * 组装本地配送时间说明
    */
   public function getDistributionTime($shop_id){
        $config_service = new Config();
        $distribution_time = $config_service->getDistributionTimeConfig($shop_id);
        if($distribution_time == 0){
            $time_desc = '';
        }else{
            $time_obj = json_decode($distribution_time['value'],true);
            if($time_obj['morning_start'] != '' && $time_obj['morning_end'] != ''){
                $morning_time_desc = '上午' . $time_obj['morning_start'] . '&nbsp;至&nbsp;' . $time_obj['morning_end'] . '&nbsp;&nbsp;';
            }else{
                $morning_time_desc = '';
            }
            
            if($time_obj['afternoon_start'] != '' && $time_obj['afternoon_end'] != ''){
                $afternoon_time_desc = '下午' . $time_obj['afternoon_start'] . '&nbsp;至&nbsp;' . $time_obj['afternoon_end'];
            }else{
                $afternoon_time_desc = '';
            }
            $time_desc = $morning_time_desc . $afternoon_time_desc;
        }
        return $time_desc;
    }
    
    /**
     * 获取订单商品满就送赠品，重复赠品累加数量
     * 赠品必须有库存
     * 创建时间：2018年1月24日12:34:10 王永杰
     */
    public function getOrderGoodsMansongGifts($goods_sku_list, $shop_id)
    {
        $res = array();
        $gift_id_arr = array();
        $goods_mansong = new GoodsMansong();
        $mansong_array = $goods_mansong->getGoodsSkuListMansong($goods_sku_list, $shop_id);
        if (! empty($mansong_array)) {
            foreach ($mansong_array as $k => $v) {
                foreach ($v['discount_detail'] as $discount_k => $discount_v) {
                    $v = $discount_v[0]['gift_id'];
                    if ($v > 0) {
                        array_push($gift_id_arr, $v);
                    }
                }
            }
        }
        // 统计每个赠品的数量
        $statistical = array_count_values($gift_id_arr);
        $promotion = new Promotion();
        foreach ($statistical as $k => $v) {
            $detail = $promotion->getPromotionGiftDetail($k);
            if ($detail['gift_goods']['stock'] > 0) {
                $detail['count'] = $v;
                array_push($res, $detail);
            }
        }
        return $res;
    }
    /**
     * 生成新的支付交易号
     * @param unknown $order_id
     * @return Ambigous <boolean, number, \think\false, string>
     */
    public function modifyOrderOutTradeNo($order_id){
        //将此订单从原来的支付订单中 分出来  (重新生成支付交易号)
        $order_model = new NsOrderModel();
        $order_bus = new OrderBusiness();
        $order_info = $order_model -> getInfo(["order_id" => $order_id], "*");
        $order_count = $order_model -> getCount(["out_trade_no" => $order_info["out_trade_no"]]);
        $retval = 0;
        if(!empty($order_info) ){
            //生成一个新的支付交易号
           $new_no = $order_bus->createOutTradeNo();
           
           //重新生成外部交易号,并且生成一笔新的支付交易
           $pay = new UnifyPay();
           $pay->createPayment(0, $new_no,  "订单",  "订单", $order_info["pay_money"], 1, 0);
           //将线下支付的订单
           $data = array("out_trade_no" => $new_no);
           $retval = $order_model ->save($data, ["order_id" => $order_id]);
           
           //如果原支付交易号下有待支付的订单,则生成新的支付交易号,并重新计算应付金额
           if($order_count > 1){
               $payment_model = new NsOrderPaymentModel();
               $payment_count = $payment_model->getCount(["out_trade_no" => $order_info["out_trade_no"]]);
               //如果此支付交易已存在,重新分配支付交易号
               if($payment_count > 0){
                   $new_order_no= $order_bus->createOutTradeNo();
                   //修改原支付交易号的支付交易号
                   $pay->modifyNo($order_info["out_trade_no"], $new_order_no);
                   //将别的订单分配一个新的外部交易号
                   $order_retval  = $order_model -> save(["out_trade_no" => $new_order_no], ["out_trade_no" => $order_info["out_trade_no"]]);
                   //重新计算外部交易号下的所需支付金额
                   $retval = $this->getPayNoOrderMoney($new_order_no);
                   if($retval <= 0){
                       return '';
                   }
               }/* else{
                   return '';
               } */
           }else{
               //如果订单交易号下没有了订单,删去订单交易
               $pay->delPayment($order_info["out_trade_no"]);
           }
           if($retval > 0){
               return $new_no;
           }
        }
        return '';
    }
    
    /**
     * 订单支付后的操作
     * @param unknown $order_pay_no
     */
    public function orderPayFollowUp($order_pay_no, $pay_type){
        $order_bus = new OrderBusiness();
         
        
        $order_model = new NsOrderModel();
        $condition['out_trade_no'] = $order_pay_no;
        $order_list = $order_model->getQuery($condition, "order_id", "");
         
        //订单后续操作
        $order_bus ->OrderPayFollowUpAction($order_pay_no, $pay_type, 0);
        
        foreach ($order_list as $k => $v) {
            runhook("Notify", "orderPay", array(
            "order_id" => $v["order_id"]
            ));
            // 判断是否需要在本阶段赠送积分
            $order = new OrderBusiness();
            $res = $order->giveGoodsOrderPoint($v["order_id"], 3);
        }
        
        $pay_type_name = OrderStatus::getPayType($pay_type);
        hook('orderOnLinePaySuccess', [
        'order_pay_no' => $order_pay_no
        ]);
        runhook('Notify', 'orderRemindBusiness', [
        "out_trade_no" => $order_pay_no,
        "shop_id" => 0
        ]); // 订单提醒
    }
     
}
